<template>
	<div>
		<a-radio-group v-model:value="radioValue" button-style="solid" class="radio-wrap mt-4 mb-2">
			<a-radio-button value="2">线索资料</a-radio-button>
			<a-radio-button value="1">线索动态</a-radio-button>
		</a-radio-group>
		<!-- 客户动态展示 -->
		<template v-if="radioValue === '1'">
			<a-tabs v-model:activeKey="activeTab" size="small" @change="getRecords()" class="tab-wrap">
				<a-tab-pane key="" tab="全部"> </a-tab-pane>
				<a-tab-pane key="0" tab="跟进记录"></a-tab-pane>
				<a-tab-pane key="1" tab="通话记录"></a-tab-pane>
				<a-tab-pane key="2" tab="操作记录"></a-tab-pane>
			</a-tabs>
			<div
				v-loading="recordLoading"
				class="scoll-view scrollbar-thumb"
				:style="{ height: recordHeight + 'px' }"
				@scroll="onBottom"
			>
				<a-timeline>
					<a-timeline-item v-for="(item, index) in recordList" :key="index">
						<div class="mt-2">
							<span style="font-size: 16px; font-weight: 500; color: #666666">{{ item.createAt }}</span>
							<div
								class="mt-2 border border-solid border-[var(--border-color-base)]"
								style="padding: 15px 30px; background: #f7f7f7; border: none"
							>
								<div class="flex justify-between">
									<div v-if="item.type === 2">{{ item.title }}</div>
									<div v-else>
										<a-space v-if="item.type === 0">
											<span style="margin-right: 20px">跟进记录</span>
											<a-tag>{{ followTypeEnum[item.followType] }}</a-tag>
											<a-tag v-if="item.customerLevelName">{{ item.customerLevelName }}类线索</a-tag>
										</a-space>
										<a-space v-if="item.type === 1">
											<span>通话记录</span>
											<a-tag>{{ item.recordFlag === '1' ? '已接通' : '未接通' }}</a-tag>
											<a-tag v-if="item.callType">{{ ['呼出', '呼入'][parseInt(item.callType)] }}</a-tag>
										</a-space>
									</div>
									<div class="flex">
										<a-tag v-if="item.type === 1 && item.communicationType !== null" class="mr-[12px]">{{
											['线路外呼', '4G多卡话机'][item.communicationType]
										}}</a-tag>
										<div>{{ item.createAt }}</div>
									</div>
								</div>
								<div v-if="item.type === 0" class="min-h-[100px] text-gray-500 pt-4">
									{{ item.content }}
								</div>
								<div v-if="item.type === 1" class="h-[100px] text-gray-500">
									<div>联系号码：{{ item.contactPhone || '-' }}</div>
									<div v-if="item.type === 1 && item.recordUrl && item.recordFlag === '1'" class="mt-[10px]">
										<audio controls ref="audio" class="aud">
											<source :src="item.recordUrl" />
										</audio>
									</div>
								</div>
								<div v-if="item.type === 2" class="h-[100px]">
									<div
										v-if="item.title === '回收公海' || item.operateType === 7"
										class="min-h-[100px] text-gray-500 pt-4"
									>
										{{ item.content }}
									</div>
									<div v-else-if="item.title === '转让线索'" class="text-gray-500 w-[80%] mt-4">
										<a-row>
											<a-col :span="24">
												<span>线索名称：</span>
												<span>{{ item.content || '-' }}</span>
											</a-col>
											<a-col :span="12">
												<span>转让人：</span>
												<span>{{ item.transName || '-' }}</span>
											</a-col>
											<a-col :span="12">
												<span>接收人：</span>
												<span>{{ item.actionName || '-' }}</span>
											</a-col>
										</a-row>
									</div>
									<div v-else class="text-gray-500 w-[80%] mt-4">
										<a-row>
											<a-col :span="24">
												<span>线索名称：</span>
												<span>{{ item.customerName || '-' }}</span>
											</a-col>
											<a-col :span="12">
												<span>职位：</span>
												<span>{{ item.post || '-' }}</span>
											</a-col>
											<a-col :span="12">
												<span>线索等级：</span>
												<span>{{ item.customerLevelName || '-' }}</span>
											</a-col>
											<a-col :span="12">
												<span>手机：</span>
												<span>{{ item.contactPhone || '-' }}</span>
											</a-col>
											<a-col :span="12">
												<span>联系人：</span>
												<span>{{ item.contactPerson || '-' }}</span>
											</a-col>
										</a-row>
									</div>
								</div>
								<div class="flex justify-end">
									<a-space :size="20">
										<div
											v-if="item.type === 0"
											style="margin-right: 80px; font-size: 15px; font-weight: 500; color: #666666"
										>
											关联联系人：{{ item.actionName }}
										</div>
										<div style="font-size: 15px; font-weight: 500; color: #666666">
											操作人：{{ item.createUserName }}
										</div>
									</a-space>
								</div>
							</div>
						</div>
					</a-timeline-item>
				</a-timeline>
				<template v-if="!recordLoading">
					<div v-show="!loading">
						<a-empty v-if="recordList.length === 0" style="padding: 100px 0" />
						<div v-else>
							<div v-if="recordList.length >= total" class="text-center text-gray-500">没有更多了</div>
							<div v-else ref="loadmore" class="text-center text-gray-500">下拉加载更多</div>
						</div>
					</div>
					<div v-show="loading" class="text-center text-gray-500">正在加载</div>
				</template>
			</div>
		</template>
		<!-- 客户资料展示 -->
		<template v-if="radioValue === '2'">
			<el-card :body-style="{ padding: '4px 16px 8px' }" class="mt-2" style="box-shadow: none">
				<div class="text-base border-0 border-l-4 border-solid border-[#108ee9] pl-2 my-3 flex justify-between">
					<span>基本信息</span>
					<template v-if="hasPerm('bizCluePurposeDetailEdit')">
						<el-text v-if="!editStatus" class="mx-1 cursor-pointer" type="primary" @click="onInfoEdit">编辑</el-text>
						<el-space v-else>
							<el-text class="mx-1 cursor-pointer" @click="onInfoCancel">取消</el-text>
							<el-text class="mx-1 cursor-pointer" type="primary" @click="onInfoSave">保存</el-text>
						</el-space>
					</template>
				</div>
				<a-form v-if="!editStatus" :label-col="{ style: { width: '100px' } }" class="form_label">
					<a-form-item label="线索名称"> {{ props.info.customerName || '-' }}</a-form-item>
					<a-form-item label="所属地区">{{ props.info.district || '-' }}</a-form-item>
					<a-form-item label="线索地址">{{ props.info.customerAddress || '-' }}</a-form-item>
					<a-form-item label="所属行业">{{ props.info.industry || '-' }}</a-form-item>
					<a-form-item label="注册日期">{{ props.info.regTime || '-' }}</a-form-item>
					<a-form-item label="线索来源">{{ props.info.customerFrom || '-' }}</a-form-item>
					<a-form-item label="备注">{{ props.info.remark || '-' }}</a-form-item>
				</a-form>
				<a-form
					v-else
					ref="formRef"
					:model="form"
					:rules="rules"
					:label-col="{ style: { width: '100px' } }"
					class="form_label"
				>
					<a-form-item label="线索名称" name="customerName">
						<!-- <a-input v-model:value="form.customerName"></a-input> -->
						<a-input-group compact>
							<a-form-item-rest>
								<a-select v-model:value="form.customerType" placeholder="请选择" style="width: 120px">
									<a-select-option :value="1">企业</a-select-option>
									<a-select-option :value="2">自然人</a-select-option>
								</a-select>
							</a-form-item-rest>
							<a-input v-model:value="form.customerName" placeholder="请输入" style="width: 300px"></a-input>
						</a-input-group>
					</a-form-item>
					<a-form-item label="所属地区">
						<area-select
							ref="areaSelectRef"
							:value="form.districtId"
							:name="form.district"
							placeholder="请选择"
							style="width: 420px"
						/>
					</a-form-item>
					<a-form-item label="线索地址">
						<a-input v-model:value="form.customerAddress" placeholder="请输入" style="width: 420px"></a-input>
					</a-form-item>
					<a-form-item label="所属行业">
						<industry-select
							ref="industrySelectRef"
							:value="form.industryId"
							:name="form.industry"
							placeholder="请选择"
							style="width: 420px"
						/>
					</a-form-item>
					<a-form-item label="注册日期">
						<a-date-picker
							v-model:value="form.regTime"
							valueFormat="YYYY-MM-DD"
							format="YYYY-MM-DD"
							placeholder="请选择"
							style="width: 420px"
						/>
					</a-form-item>
					<a-form-item label="线索来源" name="customerFrom">
						<a-select
							v-model:value="form.customerFromId"
							:options="customerFromOptions"
							placeholder="请选择"
							style="width: 420px"
							@change="fromChange"
						></a-select>
					</a-form-item>
					<a-form-item label="备注">
						<a-textarea v-model:value="form.remark" :rows="3" placeholder="请输入" style="width: 420px"></a-textarea>
					</a-form-item>
				</a-form>
			</el-card>
			<el-card :body-style="{ padding: '4px 16px 8px' }" class="mt-4" style="box-shadow: none">
				<div class="text-base border-0 border-l-4 border-solid border-[#108ee9] pl-2 my-3">系统信息</div>
				<a-form :label-col="{ style: { width: '100px' } }" class="form_label">
					<a-form-item label="创建人">{{ props.info.createUserName || '-' }}</a-form-item>
					<a-form-item label="录入方式">{{ customerRecordEnum[props.info.receiveWay] || '-' }}</a-form-item>
					<a-form-item label="掉保时间">{{ props.info.dropTime || '-' }}</a-form-item>
					<a-form-item label="创建时间">{{ props.info.createAt || '-' }}</a-form-item>
					<a-form-item label="前跟进人">{{ props.info.followUpBefperson || '-' }}</a-form-item>
					<a-form-item label="线索类型">{{ props.info.clueType || '-' }}</a-form-item>
				</a-form>
			</el-card>
		</template>
	</div>
</template>
<script setup>
	import { customerRecordEnum, followTypeEnum } from '@/views/biz/contractManagement/enum/contractEnum'
	import { useRouter } from 'vue-router'
	import areaSelect from './areaSelect.vue'
	import industrySelect from './industrySelect.vue'
	import customerSourceApi from '@/api/biz/crm/customerSourceApi'
	import customerApi from '@/api/biz/customerApi'

	const router = useRouter()
	const props = defineProps({
		info: {
			type: Object,
			default: () => ({})
		},
		/**
		 * 获取记录列表
		 */
		getRecord: {
			type: Function
		},
		/**
		 * 获取联系人列表
		 */
		getPersonList: {
			type: Function
		},
		/**
		 * 公海还是私海
		 */
		type: {
			type: String
		}
	})
	const emits = defineEmits(['clueSave'])
	onBeforeMount(() => {
		getRecords()
	})

	const recordHeight = ref(0)
	const resetRecordHeight = () => {
		clearTimeout(timer.value)
		return new Promise((resolve) => {
			timer.value = setTimeout(() => {
				clearTimeout(timer.value)
				const clueDetailDrawerBodyRef = document.querySelector('#clueDetailDrawerBody')
				const { height: drawerBodyHeight } = clueDetailDrawerBodyRef.getBoundingClientRect()
				const clueDetailPersonWrapRef = document.querySelector('#clueDetailPersonWrap')
				const { height: personHeight } = clueDetailPersonWrapRef.getBoundingClientRect()
				recordHeight.value = drawerBodyHeight - personHeight - 200
				resolve()
			}, 500)
		})
	}

	/**
	 * 获取客户来源选项
	 */
	const customerFromOptions = ref([])
	customerSourceApi.list().then((res) => {
		customerFromOptions.value = res.map((item) => {
			return {
				value: item.id,
				label: item.name
			}
		})
	})
	const fromChange = (select, option) => {
		form.value.customerFromId = select
		form.value.customerFrom = option.label
	}

	const formRef = ref()
	const areaSelectRef = ref(null)
	const industrySelectRef = ref(null)
	const editStatus = ref(false)
	const onLoading = ref(false)
	const form = ref({})
	const rules = {
		customerName: [{ required: true, message: '请输入线索名称', trigger: 'blur' }]
	}
	const onInfoEdit = () => {
		form.value = { ...props.info }
		editStatus.value = true
	}
	const onInfoCancel = () => {
		editStatus.value = false
	}
	const onInfoSave = () => {
		if (areaSelectRef.value.select && areaSelectRef.value.select.length > 0) {
			form.value.districtId = areaSelectRef.value.select.join(',')
			form.value.district = areaSelectRef.value.areaName
		}
		if (industrySelectRef.value.select) {
			form.value.industryId = industrySelectRef.value.select
			form.value.industry = industrySelectRef.value.industryName
		}
		formRef.value.validate().then(() => {
			onLoading.value = true
			customerApi
				.updateClue(form.value)
				.then(() => {
					onLoading.value = false
					emits('clueSave')
					onInfoCancel()
				})
				.finally(() => {
					onLoading.value = false
				})
		})
	}

	/**
	 * 获取跟进记录
	 */
	const radioValue = ref('2')
	const activeTab = ref(undefined)
	const recordParams = ref({
		current: 1,
		size: 10,
		type: '',
		customerCode: props.info.customerCode
	})
	const recordLoading = ref(true)
	const getRecords = async () => {
		recordLoading.value = true
		recordList.value = []
		total.value = 0
		await resetRecordHeight()
		recordParams.value = {
			current: 1,
			size: 10,
			type: activeTab.value ? activeTab.value : '',
			customerCode: props.info.customerCode
		}
		props
			.getRecord(recordParams.value)
			.then((res) => {
				recordList.value = res.records
				total.value = res.total
			})
			.finally(() => {
				recordLoading.value = false
			})
	}

	/**
	 * 下拉加载更多
	 */
	const recordList = ref([])
	const total = ref(0)
	const loadmore = ref()
	const loading = ref(false)
	const timer = ref(null)
	const onBottom = () => {
		if (recordList.value.length >= total.value) {
			return
		}
		const distance = window.innerHeight - loadmore.value.getBoundingClientRect().bottom
		const clueDetailDrawerBodyRef = document.querySelector('#clueDetailDrawerBody')
		const drawerBodyScrollHeight = clueDetailDrawerBodyRef.scrollHeight
		const drawerBodyParentClientHeight = clueDetailDrawerBodyRef.parentNode.clientHeight
		const distanceVal = drawerBodyParentClientHeight - drawerBodyScrollHeight - 20
		if (distance > distanceVal) {
			loading.value = true
			clearTimeout(timer.value)
			timer.value = setTimeout(() => {
				clearTimeout(timer.value)
				recordParams.value.size += 10
				props
					.getRecord(recordParams.value)
					.then((res) => {
						recordList.value = res.records
					})
					.finally(() => {
						loading.value = false
					})
			}, 500)
		}
	}

	defineExpose({
		radioValue,
		getRecords
	})
</script>
<style lang="less" scoped>
	.radio-wrap :deep(.ant-radio-button-wrapper) {
		height: auto;

		font-weight: 500;
	}

	.tab-wrap {
		margin-top: 5px;
		margin-bottom: 20px;
		background: #f7f7f7;
		& :deep(.ant-tabs-nav) {
			margin-bottom: 0;
		}
		& :deep(.ant-tabs-tab) {
			padding: 8px 20px;
			&:first-child {
				padding: 8px 36px;
			}
			& .ant-tabs-tab-btn {
				font-size: 14px;
				font-weight: 500;
				color: #333333;
			}
			&.ant-tabs-tab-active .ant-tabs-tab-btn {
				color: var(--primary-color);
			}
		}
	}
	.scoll-view {
		//height: 540px;
		overflow-y: auto;
	}

	.form_label :deep(.ant-form-item-label > label) {
		color: rgb(107 114 128);
	}
	.form_label :deep(.ant-form-item-label > label::after) {
		color: transparent;
	}

	.form_label :deep(.ant-form-item) {
		margin-bottom: 4px;
	}
</style>
